//
//  TableController.m
//  TianyaGuest
//
//  Created by liuwenyang on 14-8-19.
//  Copyright (c) 2014年 liuwenyang. All rights reserved.
//

#import "LBEasyTableController.h"
#import <objc/message.h>
#import <MJRefresh.h>
#import <LBEmptyData/UIView+LBEmptyData.h>
#import <UIScrollView+LBRefreshAndMoreTableView.h>
#define kPageSize 10
#define realRow(indexPath) [self tableViewStyle] == UITableViewStylePlain ? indexPath.row : indexPath.section

typedef NS_ENUM(NSUInteger, HeaderOrFooter) {
    Header = 0,
    Footer
};

@interface LBEasyTableController () <LBEasyTableViewCellDelegate>




@end

@implementation LBEasyTableController


-(id)initWithAutoLayout
{
    self = [super init];
    if (self) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:[self tableViewStyle]];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [self lineFootView];
    }
    return self;
}



-(id)initWithClassForCell:(Class)classForCell
{
    self = [self initWithAutoLayout];
    if (self) {
        
        _classForCell = classForCell;
        BOOL isUseNib = [_classForCell  isUseNib];
        if (isUseNib) {
            UINib *cellNib = [UINib nibWithNibName:NSStringFromClass(_classForCell) bundle:nil];
            [_tableView registerNib:cellNib forCellReuseIdentifier:NSStringFromClass(_classForCell)];
        }else{
            [_tableView registerClass:classForCell forCellReuseIdentifier:NSStringFromClass(_classForCell)];
        }
    }
    return self;
}

-(NSInteger)listTotal
{
    return self.listArray.count;
}


- (NSArray *)tableDataSource
{
    return _listArray;
}

-(UITableViewStyle)tableViewStyle
{
    return UITableViewStylePlain;
}

- (void)dealloc
{
    _delegate = nil;
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
    [_tableView removeFromSuperview];
    _tableView = nil;
    _listArray = nil;
}

#pragma mark set
-(void)setEstimatedRowHeight:(CGFloat)estimatedRowHeight
{
    _estimatedRowHeight = estimatedRowHeight;
    self.tableView.estimatedRowHeight = estimatedRowHeight;
}

-(void)setIsAutoCalculateHeight:(BOOL)isAutoCalculateHeight
{
    _isAutoCalculateHeight = isAutoCalculateHeight;
    self.estimatedRowHeight = self.estimatedRowHeight == 0 ? 50 : self.estimatedRowHeight;
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self tableViewStyle] == UITableViewStylePlain) {
        return [_listArray count];
    }
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LBEasyTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(_classForCell) forIndexPath:indexPath];
    cell.delegate = self;
    id data;
    if (self.listArray.count > 0) {
        data = [_listArray objectAtIndex:realRow(indexPath)];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(beforeSetDataWithModel:cell:indexPath:tableController:)]) {
        [self.delegate beforeSetDataWithModel:data cell:cell indexPath:indexPath tableController:self];
    }
    [cell configCellWithData:data atIndexPath:indexPath totalCount:self.listArray.count];
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //自动算高
    if (self.isAutoCalculateHeight) {
        return UITableViewAutomaticDimension;
    }
    
    //非自动算高
    if (self.listArray.count == 0) {
        return 0.0;
    }
    id data = [_listArray objectAtIndex:realRow(indexPath)];
    return [_classForCell heightForTableViewCell:data andIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_delegate && [_delegate respondsToSelector:@selector(didSelectedCell:dataSrc:row:)]) {
        id data = [_listArray objectAtIndex:realRow(indexPath)];
        [_delegate didSelectedCell:self dataSrc:data row:realRow(indexPath)];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([self tableViewStyle] == UITableViewStylePlain) {
        return 0.01f;
    }
    
    if (section == 0) {
        return 0.01f;
    }
    return 10.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([self tableViewStyle] == UITableViewStylePlain) {
        return 1;
    }
    return self.listArray.count;
}

+(NSString *)nodataTipsString
{
    return @"没有数据";
}

+(CGFloat)leftMargins
{
    return 0;
}

+(CGFloat)rightMargins
{
    return 0;
}



#pragma mark - TableCellDelegate

-(void)clickElement:(LBEasyTableViewCell *)tableViewCell element:(id)element cellData:(id)cellData
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didClickCellSubView:subView:subViewData:)]) {
        [self.delegate didClickCellSubView:self subView:element subViewData:cellData];
    }
}

#pragma mark - private
-(UIView *)lineFootView
{
    if (self.tableView.separatorStyle == UITableViewCellSeparatorStyleNone) {
        return [UIView new];
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake([self.class leftMargins], 0, [UIScreen mainScreen].bounds.size.width - [self.class leftMargins] - [self.class rightMargins], 0.5)];
    view.backgroundColor = [UIColor colorWithRed:232.0/255.0 green:233.0/255.0 blue:235.0/255.0 alpha:1.0];
    return view;
}

@end


@interface LBEasyRefreshTableController ()

/** 注释*/
@property(nonatomic,assign)BOOL enableInfiniteScroll;



@end


@implementation LBEasyRefreshTableController



-(id)initWithDragRefresh:(BOOL)enableDragRefresh withInfiniteScroll:(BOOL)enableInfiniteScroll classForCell:(Class)classForCell
{
    self = [super initWithClassForCell:classForCell];
    if (self) {
        if (enableDragRefresh) {
            
            __weak LBEasyRefreshTableController *weakSelf = self;
            
            [self.tableView addRefreshAction:^{
                
                [weakSelf refreshHeaderViewDidCallBackWithAnimation:YES];
                
            } loadMoreAction:nil customLogin:NO];
//            self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(forceRefresh)];
        }
        _enableInfiniteScroll = enableInfiniteScroll;
        _pageIndex = 1;
    }
    return self;
}

- (void)refreshTable:(void (^)(BOOL))block
{
    //virtual method
}

- (void)getTableMore:(void (^)(BOOL))block
{
    //virtual method
}

- (void)forceRefresh
{
    [self.tableView.mj_header beginRefreshing];
}

-(void)forceRefreshWithoutAnimation
{
    [self refreshHeaderViewDidCallBackWithAnimation:NO];
}



- (void)refreshHeaderViewDidCallBackWithAnimation:(BOOL)animation
{
   
    if (animation) {
//        [self.tableView.mj_header beginRefreshing];
    }
    self.pageIndex = 1;
    __weak LBEasyRefreshTableController  *weakSelf = self;
    [self refreshTable:^(BOOL finished) {
        
        [weakSelf.tableView lb_setEmptyNoData:[[weakSelf class] nodataTipsString]];
        if (finished) {
            
            [weakSelf finishLoadingAndResetFooter:Header];
        } else {
            [weakSelf.tableView.mj_header endRefreshing];
            NSLog(@"modelDidLoadFailure");
        }
        
    }];
}


- (void)refreshFooterViewDidCallBack
{
    [self.tableView.mj_footer beginRefreshing];
    __weak LBEasyRefreshTableController *weakSelf = self;
    ++self.pageIndex;
    [self getTableMore:^(BOOL finished) {
        if (finished) {
            
            [weakSelf finishLoadingAndResetFooter:Footer];
            
        }else{
            [weakSelf.tableView.mj_footer endRefreshing];
            NSLog(@"modelDidLoadFailure");
        }
    }];
}


-(void)finishLoadingAndResetFooter:(HeaderOrFooter)headerOrFooter
{
    if (headerOrFooter == Header) {
        [self.tableView.mj_header endRefreshing];
    }else{
        [self.tableView.mj_footer endRefreshing];
    }
    
    
    if (self.enableInfiniteScroll) {
        if (self.totalCount > self.listArray.count || self.totalPages > self.pageIndex) {
            //需要展现加载更多
            if (self.tableView.mj_footer == nil) {
                self.tableView.mj_footer  = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFooterViewDidCallBack)];
                self.tableView.mj_footer.automaticallyHidden = YES;
            }
            
        }else{
            [self.tableView.mj_footer removeFromSuperview];
//            self.tableView.tableFooterView = [[UIView alloc] init];
            self.tableView.tableFooterView = [self lineFootView];
            self.tableView.mj_footer = nil;
        }
    }else{
        [self.tableView.mj_footer removeFromSuperview];
        self.tableView.tableFooterView = [self lineFootView];
        self.tableView.mj_footer = nil;
    }
    
    //通知代理model加载完成
    if (self.delegate && [self.delegate respondsToSelector:@selector(modelDidLoadFinished:)]) {
        [self.delegate modelDidLoadFinished:self];
    }
}








-(void)dealloc
{
    NSLog(@"tablecontroller销毁了");
}

@end





















